import { createStore } from 'vuex'

export default createStore({
  state: {
    cartList: []
  },
  mutations: {
    // mutations唯一的目的就是修改state中状态
    // mutations中的每个方法尽可能完成的事件比较单一
    addCounter(state, payload) {
      payload.count += 1;
    },
    addToCart(state, payload) {
      payload.checked = false;
      state.cartList.push(payload);
    },
    checkClick(state, payload) {
      payload.checked = !payload.checked
    }
  },
  actions: {
    addCart(context, payload) {
      return new Promise((res, rej) => {
        // 1.查找之前数组中是否有该商品
        let oldProduct = context.state.cartList.find(item => item.iid === payload.iid);
        // 2.判断oldProduct
        if (oldProduct) { // 数量+1
          context.commit('addCounter', oldProduct);
          res('该商品数量 +1')
        } else {
          payload.count = 1 // 添加新的商品
          context.commit('addToCart', payload);
          res('成功添加该商品')
        }
      })
    }
  },
  getters: {
      cartLength (state) {
        return state.cartList.length
      },
      cartList (state) {
        return state.cartList
      },
      totalPrice(state) {
        const cartList = state.cartList;
        return '￥' + cartList.filter(item => {
          return item.checked
        }).reduce((preValue, item) => {
          return Number((preValue + item.count * item.price).toFixed(2))
        }, 0)
      },
      totalCount(state) {
        const cartList = state.cartList;
        return cartList.filter(item => {
          return item.checked
        }).reduce((preValue, item) => {
          return preValue + item.count 
        }, 0)
      },
      // overCart(state) {
      //   let cartList = state.cartList.filter(item => {
      //     return item.checked = false
      //   })
        
      // }
    }
})
